package com.example.testcontentprovider;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.view.Menu;
import android.widget.TextView;

public class ContactActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		TextView contactView = (TextView) findViewById(R.id.contactView);
		Cursor cursor = getContact();
		while(cursor.moveToNext()){
			String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			//debugDialog(displayName);
			contactView.append("Name : ");
			contactView.append(displayName);
			contactView.append("\n");	
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_contact, menu);
		return true;
	}
	
	@SuppressWarnings("deprecation")
	private Cursor getContact(){
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = { ContactsContract.Contacts._ID, 
				ContactsContract.Contacts.DISPLAY_NAME};
		String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + "='" +
				 ("1") + "'";
		String[] selectionArgs = null;
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED DESC";
		return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
		
	}
	public void debugDialog(String str){
		AlertDialog.Builder ad = new AlertDialog.Builder(ContactActivity.this);
		ad.setTitle("Debug Dialog");
		ad.setMessage(str);
		ad.setPositiveButton("OK", new OnClickListener (){
			public void onClick(DialogInterface dialog, int arg1) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		ad.setCancelable(true);
		ad.setOnCancelListener(new OnCancelListener(){

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
			
		});
		ad.show();
	}	

}
